package com.easyj.admin.edu.serviceimpl;

import java.util.List;
import java.util.Date;

import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.security.SecurityManager;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.DelegationState;
import org.activiti.engine.task.TaskQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.easyj.admin.edu.service.AwardService;
import com.easyj.admin.activiti.utils.ProcessUtils;
import com.easyj.admin.activiti.vo.SimpleApproveVO;
import com.easyj.admin.db.mapper.AwardMapper;
import com.easyj.base.exception.*;
import com.easyj.base.security.SimpleUser;
import com.easyj.base.security.service.SecurityUtil;
import com.easyj.base.enums.SimpleApplyStatusEnum;
import com.easyj.base.cache.SysCacheUtil;
import com.easyj.base.common.page.Page;
import com.easyj.admin.db.model.Award;
import com.easyj.admin.db.model.AwardQO;


/**
 * 简单一级审批，委托办理
 * @author hjf
 *
 */

@Service
public class AwardServiceImpl implements AwardService{    
	
	@Autowired
	private  AwardMapper awardMapper;
	
	@Autowired
    private ProcessRuntime processRuntime;
	
	@Autowired
    private TaskRuntime taskRuntime;
	
	@Autowired
	private RuntimeService runtimeService;
	
	@Autowired
	private TaskService taskService;
	
	 @Autowired
	 private  SecurityManager securityManager;
	
	  	
	public Page<Award> findPage(AwardQO filter){
	    Long total=awardMapper.countByExample(filter);
		List<Award> rows=null;
		if(total>0l){
			filter.getPage().resetOffsetByTotal(total);
		    rows= awardMapper.selectByExample(filter);
		}
		
		Page<Award> rtn=new Page<Award>(rows,total,filter.getPage());
		return rtn;
	}


   	public List<Award> findList(AwardQO filter){
        return awardMapper.selectByExample(filter);
    }
	public long count(AwardQO filter){
	     return awardMapper.countByExample(filter);
	}	


	public Award findById(Long id){
		Award entity= awardMapper.selectByPrimaryKey(id);
		return entity;
	}
	
	
	@Transactional
	public int  apply(Award entity) throws EasyjException{
		entity.setApplyTime(new Date());
		SimpleUser usr=SecurityUtil.getOperator();
		entity.setApplicantId(usr.getId());
		entity.setDeptId(usr.getDepartmentId());
		entity.setStatus(SimpleApplyStatusEnum.WAITING.getKey());	
		entity.setApplyTime(new Date());
		int rtn= awardMapper.insert(entity);
		
		//start process,set businessKey=entity.id
		String businessKey = entity.getId().toString(); //业务key,

		processRuntime.start(ProcessPayloadBuilder
	                        .start()
	                        .withProcessDefinitionKey(ProcessDefKey)
	                        .withName(entity.getApplyName())
	                        .withBusinessKey(businessKey)
	                        .build());
		return rtn;
	}
	
	@Transactional
	public void approve(SimpleApproveVO approveVO) throws EasyjException{
		
		 TaskQuery query=taskService.createTaskQuery();
		 query.taskId(approveVO.getTaskId());	
		//本人任务
		 String authenticatedUserId = securityManager.getAuthenticatedUserId();
		 List<String> userGroups = securityManager.getAuthenticatedUserGroups();
		 query.or().taskCandidateOrAssigned(authenticatedUserId,userGroups).endOr();
	     //taskRuntime 不返回delegationState， Task task=taskRuntime.task();坑          
		 org.activiti.engine.task.Task task=query.singleResult();			
		
		if(!task.getBusinessKey().equals(approveVO.getEntityId().toString())) {
			throw new  ValidateException("数据不符合要求！");
		}		

		Award entity=awardMapper.selectByPrimaryKey(approveVO.getEntityId());
		if(entity.getStatus().intValue()!=SimpleApplyStatusEnum.WAITING.getKey()){
			throw new  ValidateException("状态不是‘等待审批’！");
		}
			
		//update entity
		if(approveVO.isPassed()){
		    entity.setStatus(SimpleApplyStatusEnum.PASSED.getKey());
	    }else {
	    	entity.setStatus(SimpleApplyStatusEnum.REJECT.getKey());
	    }
		
		entity.setApproveComment(approveVO.getComment());
		entity.setApproveId(approveVO.getApproveUserId());
		entity.setApproveTime(new Date());		
		awardMapper.updateByPrimaryKeySelective(entity);
		
		//加上审批意见
		ProcessUtils.addComment(task,SecurityUtil.getOperatorId().toString(), approveVO.isPassed(), approveVO.getComment());		
        
		//如果是委托任务		
		DelegationState delegationState = task.getDelegationState();
		if(delegationState!=null) {
	        if (delegationState.equals(DelegationState.PENDING)) {
				taskService.resolveTask(approveVO.getTaskId());
		        taskService.complete(approveVO.getTaskId());
		        return;
			}else if (delegationState.equals(DelegationState.RESOLVED)) {
				throw new  ValidateException("委托任务的状态不是PENDING！");
			}
		}
		if(StringUtils.isBlank(task.getAssignee())){
		  taskRuntime.claim(
               TaskPayloadBuilder.claim().withTaskId(approveVO.getTaskId()).build());
        }
		taskRuntime.complete(
                TaskPayloadBuilder.complete()
                        .withTaskId(approveVO.getTaskId()) //.withVariables(variables)
                        .build());
		
		
	}
	
	@Transactional
	public void delegateTask(SimpleApproveVO approveVO) throws ValidateException{
		Task task=taskRuntime.task(approveVO.getTaskId());
		if(!task.getBusinessKey().equals(approveVO.getEntityId().toString())) {
			throw new  ValidateException("数据不符合要求！");
		}
		//claim
		if(StringUtils.isBlank(task.getAssignee())){
			  taskRuntime.claim(
	               TaskPayloadBuilder.claim().withTaskId(approveVO.getTaskId()).build());
	    }
		taskService.delegateTask(approveVO.getTaskId(), approveVO.getDelegateUser());
		
		//加委托
		Long userId=Long.parseLong(approveVO.getDelegateUser());		
		String comment="委托给："+SysCacheUtil.getOperatorName(userId);
		ProcessUtils.addComment(task,SecurityUtil.getOperatorId().toString(), comment);		
        
	}
	

	
	@Transactional
	public int  updateEntity(Award entity) throws EasyjException{
		
	    Award find=awardMapper.selectByPrimaryKey(entity.getId());
		if(find.getApplicantId().longValue()!=SecurityUtil.getOperatorId().longValue()) {
			throw new  ValidateException("非法操作！");
		}
		if(find.getStatus()!=SimpleApplyStatusEnum.WAITING.getKey()) {
			throw new  ValidateException("非法操作,只能修改‘等待审批’的申请！");
		}
		entity.setStatus(find.getStatus());	
		entity.setApproveTime(find.getApproveTime());
		
		int rtn= awardMapper.updateByPrimaryKey(entity);
		return rtn;
	}
	
	/**
     * 按实体ID取消流程
	 */ 
	@Transactional(rollbackFor=Exception.class)
	public int  cancel(Long id) throws EasyjException{
		Award find=awardMapper.selectByPrimaryKey(id);
		if(find.getApplicantId().longValue()!=SecurityUtil.getOperatorId().longValue()) {
			throw new  ValidateException("非法操作！");
		}
		if(find.getStatus()!=SimpleApplyStatusEnum.WAITING.getKey()) {
			throw new  ValidateException("只能取消‘等待审批’的申请！");
		}
		
		find.setStatus(SimpleApplyStatusEnum.CANCEl.getKey());
		find.setApproveTime(new Date()); //共用
		
		int rtn= awardMapper.updateByPrimaryKey(find);
		
		
		//取消,delete流程实例 
		org.activiti.engine.runtime.ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(find.getId().toString(), ProcessDefKey).active().singleResult();
		runtimeService.deleteProcessInstance(processInstance.getId(), "申请人取消");
		
		return rtn;
	}
   


	/** 按流程ID取消流程
	 * 
	@Transactional(rollbackFor=Exception.class)
	public int  cancelByProId(String proId) throws EasyjException{
		org.activiti.api.process.model.ProcessInstance  processInstance= processRuntime.processInstance(proId);                
		Long entityId=Long.parseLong(processInstance.getBusinessKey());
		Award find=awardMapper.selectByPrimaryKey(entityId);
		if(find.getApplicantId().longValue()!=SecurityUtil.getOperatorId().longValue()) {
			throw new  ValidateException("非法操作！");//只能自已取消
		}
		if(find.getStatus()!=SimpleApplyStatusEnum.WAITING.getKey()) {
			throw new  ValidateException("只能取消‘等待审批’的申请！");
		}
		
		find.setStatus(SimpleApplyStatusEnum.CANCEl.getKey());
		find.setApproveTime(new Date()); //共用
		
		int rtn= awardMapper.updateByPrimaryKey(find);
		
		processRuntime.delete(ProcessPayloadBuilder
                .delete().withProcessInstance(processInstance).withReason( "申请人取消")               
                .build());
		
		return rtn;
	}
     */
	
}
